package com.jackson0714.common.aspect;
/**
  * @Description:服务间api调用异常处理切面
  * @Version v1.0.0
  * @author zhangpeng148
  * @date 2022/1/21 16:00
  */

import com.jackson0714.common.enums.InternalApi;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
@Aspect
public class InternalApiAspect {

    @Around("@annotation(com.jackson0714.common.enums.InternalApi) || @within(com.jackson0714.common.enums.InternalApi)")
    public Object operate(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object proceed = null;
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = methodSignature.getMethod();
        InternalApi internalApi = AnnotationUtils.getAnnotation(method, InternalApi.class);
        if(null != internalApi) {
            try {
                proceed = proceedingJoinPoint.proceed();
            } catch (Throwable throwable) {
                RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
                HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse();
                response.setStatus(internalApi.httpStatus());
                throw throwable;
            }
        }
        return proceed;
    }
}
